package com.gg.communication.communication.udp.client;

import com.gg.communication.communication.BaseCommunication;
import com.gg.communication.util.ByteUtil;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sakura
 * @since 2025-06-16
 */

public class UdpClient extends BaseCommunication {
    private UdpClient() {

    }

    private static Map<String, UdpClient> udpClientMap = new HashMap();

    private DatagramSocket socket;

    //static {
    //    System.out.println("asdfffff");
    //    getInstance(new UdpClient());
    //}

    public static BaseCommunication initInstance(String host, int port) {
        synchronized (UdpClient.class) {
            if (udpClientMap.get(host + ":" + port) == null) {
                UdpClient client = new UdpClient();
                client.setPort(port);
                client.setHost(host);
                udpClientMap.put(host + ":" + port, client);
            }
        }
        return udpClientMap.get(host + ":" + port);
    }


    @Override
    public void startCommunication() throws SocketException {
        this.socket = new DatagramSocket();
    }

    @Override
    public void doCommunicationSend(byte[] msg, String host, int port) throws IOException {
        DatagramPacket packet = new DatagramPacket(task.message, task.message.length, InetAddress.getByName(host), port);
        socket.send(packet);
    }

    @Override
    public byte[] doReceive() throws Exception {
        byte[] buffer = new byte[1024];
        DatagramPacket responsePacket = new DatagramPacket(buffer, buffer.length);
        socket.receive(responsePacket);
        byte[] responseData = new byte[responsePacket.getLength()];
        System.arraycopy(responsePacket.getData(), responsePacket.getOffset(), responseData, 0, responsePacket.getLength());
        System.out.println(ByteUtil.byteArrayToHexString(responseData));
        return responseData;
    }

}
